<?php


namespace app\mqtt\controller;

/**
 * 报警模块
 * Class Contacts
 * @package app\userapi\controller
 */
class Contacts extends Base
{
    /**
     * 功能说明 获取用户报警规则
     * author 郑
     * time 2021-05-06 14:24
     */
    public function getContacts(){
        $search = request()->param();
        $search['str'] = isset($search['str']) ? $search['str'] : "";
        $whereLike = "name like '%{$search['str']}%' or remark like '%{$search['str']}%'";
        $res = db('contacts')
            ->order("id desc")
            ->where(['uid'=>$this->accessData['uid']])
            ->where($whereLike)
            ->paginate($search['pageSize'], false, ['page' => $search['page']]);
        foreach ($res as $k=>$v){
            $v['create_time']=date("Y-m-d h:i:s",$v['create_time']);
            $baud=json_decode($v['baud']);
            $v['baud_title']="";
            foreach ($baud as $value){
                $title="";
                if($value==1){
                    $title="离线报警";
                }
                else  if($value==2){
                    $title="信号强度报警";
                }
                else  if($value==3){
                    $title="流量";
                }
                $v['baud_title']= $v['baud_title'].$title.'，';
            }
            $model=json_decode($v['model']);
            $v['model_title']="";
            foreach ($model as $value){
                $title="";
                if($value==1){
                    $title="手机号";
                }
                else  if($value==2){
                    $title="邮箱";
                }
                $v['model_title']= $v['model_title'].$title.'，';
            }


            $res[$k]=$v;
        }
        suc($res);
    }

    /**
     * 功能说明 获取报警规则关联用户信息
     * author 郑
     * time 2021-06-07 15:34
     */
    public function getUser($id)
    {
        $res=db("contacts_user_bind")->field("user_id")->where(['contacts_id'=>$id])->select();
        $userList=[];
        foreach ($res as $v){
            $userList[]=db("contacts_user")->where(['id'=>$v['user_id']])->find();
        }
       return $userList;
    }


    /**
     * 功能说明 发送电子邮件
     * author 郑
     * time 2021-05-07 15:26
     */
    public function sendEmail(){
        $to = "376087078@qq.com";
        $subject = "Test mail";
        $message = "Hello! This is a simple email message.";
        $from = "ebyte@ebyte.com";
        $headers = "From: $from";
        mail($to,$subject,$message,$headers);
        echo "Mail Sent.";
    }

    /**
     * 功能说明 发送手机短信警报
     * author 郑
     * time 2021-05-07 15:46
     */
    public function sendPhone(){

    }


    /**
     * 功能说明  离线报警检测
     * 循环检测所有redis报警设置，模块消息通知
     * author 郑
     * time 2021-06-07 16:21
     */
    public function exAllContacts()
    {
        set_time_limit(0);
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $activity_all = $redis->keys('device*');

        foreach ($activity_all as $v) {
            $isRun = $redis->exists($v);
            if (!$isRun) {
                continue;
            };
            $contact =json_decode($redis->get($v),true) ;
            //获取设备当前信息
            $content =json_decode($redis->get('content'.$contact['id']),true);
            //获取设备是否正常
            if($contact['type']=="timeOut"){
                if($content['time_out_status']==2){
                    echo "设备报警状态已异常，不进行处理\r\n";
                    $redis->del($v);
                    continue;
                }
                else if($content['last_login_time']>$contact['time']){
                    echo "设备已再次期间登陆过，不进行处理\r\n";
                    $redis->del($v);
                    continue;
                }
                else if($contact['time']<time())
                {
                    echo "当前时间".date("H:i:s")."\r\n";
                    echo "设备最后上线时间".date("H:i:s",$content['last_login_time'])."\r\n";
                    echo "报警设置最终时间".date("H:i:s",$contact['time'])."\r\n";
                    echo "开始报警\r\n";
                    //添加报警记录
                    $contactDetail['code']=$content['code'];
                    $contactDetail['eid']=$content['id'];
                    $contactDetail['create_time']=$content['create_time'];
                    $contactDetail['type']=1;
                    $contactDetail['info']="设备离线超过".$contact['contacts']['timeOut']."分钟";
                    $contactDetail['uid']=$contact['contacts']['uid'];
                    $contactDetail['status']=1;
                    db('contacts_log')->insert($contactDetail);
                    //设备更新为异常
                    db('equipment_content')->where(['id'=>$content['id']])->update(['time_out_status'=>2]);

                    //发送联系人报警信息

                    $redis->del($v);
                    echo "报警完成\r\n";
                }
                else{
                    echo "未到报警时间，等待下次\r\n";
                }
            }
        }
        echo "5秒后开始下一次检测\r\n";
        for ($i=5;$i>0;$i--){
           // echo $i."秒后开始下一次检测\r\n";
            sleep(1);
        }
        $this->exAllContacts();
    }

    /**
     * 功能说明  获取报警消息列表
     * author 郑
     * time 2021-06-18 13:18
     */
    public function getConotacts(){
        $search = request()->param();
        $search['pageSize']=isset($search['pageSize'])?$search['pageSize']:20;
        $search['page']=isset($search['page'])?$search['page']:1;
        $where = [];
        if (isset($search['id'])) {
            $where['eid'] = $search['id'];
        }
        $res = db('contacts_log v')
            ->field("v.*")
            ->order("v.id desc")
            ->where($where)
            ->paginate($search['pageSize'], false, ['page' => $search['page']]);
        foreach ($res as $k => $v) {
            $v['create_time'] = date("Y-m-d h:i:s", $v['create_time']);
            $res[$k] = $v;
        }
        suc($res);
}

}